package com.lixinkeji.utils

import android.content.Context
import android.net.Uri
import android.text.TextUtils
import com.luck.picture.lib.engine.CompressEngine
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnCallbackListener
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.previewlibrary.view.BasePhotoFragment.listener
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.ArrayList
import java.util.Locale

class MyCompressEngine :CompressEngine {


    override fun onStartCompress(
        context: Context?,
        list: ArrayList<LocalMedia>?,
        listener: OnCallbackListener<ArrayList<LocalMedia>>?
    ) {
        for (i in 0 until  list?.size!!){
            Luban.with(context)
                .load(list[i].realPath)
                .ignoreBy((1024 * 1.5).toInt())
                .filter { path ->
                    !(TextUtils.isEmpty(path) || path.lowercase(Locale.getDefault())
                        .endsWith(".gif"))
                }
                .setCompressListener(object : OnCompressListener {
                    override fun onStart() {

                    }

                    override fun onSuccess(index: Int, compressFile: File?) {
                        if (compressFile != null) {
                            list[i].isCompressed = true
                            list[i].compressPath = compressFile.path
                        }
                        if(i==list.size-1){
                            listener?.apply {
                                onCall(list)
                            }
                        }
                    }

                    override fun onError(index: Int, e: Throwable?) {

                    }
                }).launch()
        }

    }
}